package com.wzq.util;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class FrameUtil {
    /**
     * 获取视频的其中一帧
     * @param fileUrl       视频源
     * @param fileName      图片保存url
     * @throws IOException
     */
    public static boolean getFirst(String fileUrl,String fileName ) throws IOException {
//    String fileUrl = "C:\\mimi\\upload\\video\\1670655440973.mp4";
        boolean flag=false;
    FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(fileUrl);
        fFmpegFrameGrabber.start();
    Frame frame = null;
    //获取视频总帧数
    int frames = fFmpegFrameGrabber.getLengthInFrames();
    int i = 0;
        while (i <= frames){
        frame = fFmpegFrameGrabber.grabImage();
        //截取第10帧
        if(frame!=null && i==3){
//            String fileName = "C:\\mimi\\upload\\video\\"+System.currentTimeMillis()+".jpg";
            File file = new File(fileName);
            //创建BufferedImage对象
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage bufferedImage = converter.getBufferedImage(frame);
            flag=ImageIO.write(bufferedImage,"jpg",file);
            break;
        }
        i++;
    }
        fFmpegFrameGrabber.stop();
        fFmpegFrameGrabber.close();
        return flag;
}
}
